import {Drawer, Form, Button, List, Input, Avatar,Divider, Flex, message, Modal} from 'antd';
import { Comment } from '@ant-design/compatible';
import { useParams } from '@@/exports';
import React, {useEffect, useState,useRef} from 'react';
import {DeleteOutlined} from "@ant-design/icons";
import {keyframes} from "antd-style";
import {
    addCommentUsingPost,
    deleteCommentUsingPost,
    listCommentByPageUsingGet
} from "@/services/openAPI-backend/articleCommentController";

export type Props = {
  onClose: () => void;
  isOpen: boolean;
  data: Record<string, any>[];
};
const { confirm } = Modal;

const CommentModal: React.FC<Props> = (props) => {
    const param = useParams();
    const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateX(100%); /* 初始位置在屏幕右侧100% */
        }
        to {
            opacity: 1;
            transform: translateX(0); /* 结束位置在正常位置 */
        }
    `;
  const { isOpen, onClose,data } = props;
  const currentUser = sessionStorage.getItem('loginUser')
  const [commentList, setCommentList] = useState(data);
  const getComment = async (id) => {
    try{
      const res = await listCommentByPageUsingGet({
          articleId:id,
          pageNum: 1,
          pageSize: 10,
      });
      setCommentList(res?.data?.rows);
    }catch (e){
      console.log(e);
    }
  }

  const deleteComment = async (id) => {

    try{
      await deleteCommentUsingPost({
        id:id,
      })
      getComment(param.id);
    }catch (e) {
      alert(e)
    }
  };
  const showDeleteConfirm = (id) => {
    const recordvalue = id;
    // @ts-ignore
    confirm({
      title: '是否要删除',
      content: '评论删除不可逆',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      open: true,
      onOk() { deleteComment(recordvalue);},
      onCancel() {
        return false;
      },
    });
  };

  const[tempcomment,setTempcomment] = useState<string>("");
  const formRef = useRef(null);
  const onfinish = async (values: any) => {

    formRef.current?.resetFields()
    setTempcomment("")
    try {
      // 登录

         await addCommentUsingPost({
         context: values?.UserComment,
             articleId: param.id,
      });

      await getComment(param.id);
      return true;
    } catch (e) {
      message.error(e);
      return false;
    }
  };
  useEffect(() => {
    getComment(param.id);
  }, [param.id]);
  useEffect(() => {
    setCommentList(data)
      console.log(commentList)
  }, [isOpen]);
  return (
    <Drawer
      size="large"
      open={isOpen}
      title={<p style={{ fontSize: '20px', fontWeight: 'bold', marginTop: "20px" }}>评论</p>}
      footer={null}
      onClose={onClose}
      style={{
        borderBottomLeftRadius: '10px',
        borderTopLeftRadius: '10px',
        borderWidth: '0px',
        borderTop: 0,
        borderLeft: 0,
        borderRight: 0,
        borderBottom: 0,
      }}
    >
      <List
        className="comment-list"
        footer={<a style={{color:"gray",fontSize:'14px'}}>{`${commentList?.length} 回复`}</a>}
        itemLayout="horizontal"
        dataSource={commentList}
        renderItem={(item) => (
          <li>
            <Comment
              author={item.userName}
              avatar={
                 <Avatar
                src={item.avatar === null
                  ? 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
                  : item.avatar}

shape="square"
/>
              }
              content={item.context}
              datetime={item?.updateTime.substring(0, 10)}
              style={{
                display: 'inline-block',
                fontSize: '16px',
              }}
            />
            <span
              style={{
                display: 'inline-block',
                width: 1,
                height: 0.1,
                float: 'right',
                marginTop: 40,
              }}
            >
              <Button
                key="submit"
                type="text"
                ghost="true"
                size="small"
                disabled={
                  currentUser?.userRole === 'admin' || currentUser?.userId === item.userId
                    ? true
                    : false
                }
                styles={{
                  width: 0.1,
                  height: 0.1,
                  padding: 0,
                  fontSize: '12px',
                }}
                shape="circle"
                icon={<DeleteOutlined />}
                onClick={() => {
                  showDeleteConfirm(item.id);
                }}
              ></Button>
            </span>
          </li>
        )}
      />
      <Divider />
      <Form name="basic" layout={'vertical'} onFinish={onfinish} ref={formRef} >
        <Form.Item label={<p style={{fontSize: '16px',fontWeight: 'bold'}}>留下您的评论吧</p>} name="UserComment">
          <Input.TextArea size="large" showCount="true" />
        </Form.Item>
        <Form.Item>
          <Flex justify={'flex-start'}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Flex>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default CommentModal;
